import React, { PureComponent } from 'react';
import { Radio, Tabs, Table, Row, Col, Icon, Button } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import { InputEditor, NumberView } from '@/components/BaseTable';
// import dayjs from 'dayjs';
import styles from '../../../index.less';

const { TabPane } = Tabs;
const { Column, ColumnGroup } = Table;

@connect(state => ({
  signDates: state.ContractPlanProductTypeDetail.signDates,
  contractPlanItems: state.ContractPlanProductTypeDetail.contractPlanItems,
  canSignRoomCount: state.ContractPlanProductTypeDetail.canSignRoomCount,
  isParking: state.ContractPlanProductTypeDetail.isParking,
}))
export default class ProductTypeDetail extends PureComponent {
  // static getDerivedStateFromProps(nextProps, prevState) {
  //   // 4. Updating state based on props
  //   // 7. Fetching external data when props change
  // }

  constructor(props) {
    // 1. Initializing state
    super(props);
    this.state = {
      year: null,
      month: null,
      initYear: new Date().getUTCFullYear(),
      initMonth: new Date().getUTCMonth() + 1,
    };
  }

  // eslint-disable-next-line react/sort-comp
  componentWillReceiveProps(nextProps) {
    const { initYear, month, year } = nextProps;
    this.setState({ initYear, initMonth: month, month, year });
    // let initYear = 0;
    // let initMonth = 1;
    // console.log(nextProps)
    // if (!this.state.year && signDates && signDates.length > 0) {
    //   const isThatYear = _.filter(signDates, elementYear => elementYear.key * 1 === new Date().getUTCFullYear());
    //   if (isThatYear.length > 0) {
    //     initYear = isThatYear[0].key * 1;
    //     initMonth = new Date().getUTCMonth() + 1;
    //   }
    //   if (isThatYear.length <= 0) {
    //     signDates.forEach(elementYear => {
    //       elementYear.months.forEach(elementMonth => {
    //         if (elementMonth.editable && elementMonth.clickable && initYear === 0) {
    //           initYear = elementYear.key * 1;
    //           initMonth = elementMonth.key * 1;
    //         }
    //       });
    //     });
    //   }
    //   this.setState({ initYear, initMonth });
    //   this.props.dispatch({
    //     type: 'ContractPlanProductTypeDetail/changeYearMonth',
    //     payload: {
    //       initYear,
    //       month: initMonth,
    //     },
    //   });
    //   // signDates.forEach(elementYear => {
    //   //   if (dayjs(new Date(initYear, initMonth - 1, 1)) === dayjs()) {

    //   //   }
    //   //   elementYear.months.forEach(elementMonth => {
    //   //     if (elementMonth.editable && elementMonth.clickable && initYear === 0) {
    //   //       initYear = elementYear.key * 1;
    //   //       initMonth = elementMonth.key * 1;
    //   //     }
    //   //   });
    //   // });
    //   // if (dayjs(new Date(initYear, initMonth - 1, 1)) > dayjs()) {
    //   //
    //   //   this.props.dispatch({
    //   //     type: 'ContractPlanProductTypeDetail/changeYearMonth',
    //   //     payload: {
    //   //       initYear,
    //   //       month: initMonth,
    //   //     },
    //   //   });
    //   // }
    // }
    if (this.props.match.params !== nextProps.match.params) {
      const { match } = nextProps;
      this.props.dispatch({
        type: 'ContractPlanProductTypeDetail/init',
        payload: {
          data: {
            versionId: match.params.version,
            // 经营方式编码
            businessType: match.params.businessType,
            // 装修方式编码
            freeType: match.params.freeType,
            // 组团id
            groupId: match.params.group,
            pid: match.params.pid,
            // 产品属性编码
            proType: match.params.proType,
            // 产品构成编码
            productCode: match.params.productCode,
          },
        },
        // callback,
      });
    }
  }

  componentDidMount() {
    const { dispatch, match } = this.props;
    dispatch({
      type: 'ContractPlanProductTypeDetail/init',
      payload: {
        data: {
          versionId: match.params.version,
          // 经营方式编码
          businessType: match.params.businessType,
          // 装修方式编码
          freeType: match.params.freeType,
          // 组团id
          groupId: match.params.group,
          pid: match.params.pid,
          // 产品属性编码
          proType: match.params.proType,
          // 产品构成编码
          productCode: match.params.productCode,
        },
      },
      // callback,
    });
  }

  changeYear = year => {
    const items = _.filter(this.props.signDates, item => item.key === _.toNumber(year));
    let month = 0;
    if (items && items.length > 0) {
      items[0].months.forEach(item => {
        if (item.clickable && month === 0) {
          month = _.toNumber(item.key);
        }
      });
    }
    this.setState({ year: _.toNumber(year), month: _.toNumber(month) });

    this.props.dispatch({
      type: 'ContractPlanProductTypeDetail/changeYearMonth',
      payload: {
        year,
        month: _.toNumber(month),
      },
    });
  };

  changeMonth = e => {
    this.setState({ month: _.toNumber(e.target.value) });

    this.props.dispatch({
      type: 'ContractPlanProductTypeDetail/changeYearMonth',
      payload: {
        month: _.toNumber(e.target.value),
      },
    });
  };

  /* 点击添加年 */
  onEditYear = (targetKey, action) => {
    const { dispatch } = this.props;
    if (action === 'add') {
      dispatch({
        type: 'ContractPlanProductTypeDetail/addYear',
        payload: {
          params: {},
        },
      });
    }
    if (action === 'remove') {
      if (this.state.year * 1 === targetKey * 1) {
        this.setState({ year: targetKey * 1 - 1 });
        this.props.dispatch({
          type: 'ContractPlanProductTypeDetail/changeYearMonth',
          payload: {
            year: targetKey * 1 - 1,
          },
        });
      }
      dispatch({
        type: 'ContractPlanProductTypeDetail/removeYear',
        payload: {
          year: targetKey,
        },
      });
    }
  };

  getLastPlan = ({ signDates, contractPlanItems }) => {
    const year = _.last(signDates);
    const month = _.last(year.months);

    const planCurrentMonth = this.getPlan({
      contractPlanItems,
      year: year.key,
      month: month.key,
    });
    return planCurrentMonth;
  };

  getPlan = ({ contractPlanItems, year, month }) => {
    if (!contractPlanItems || contractPlanItems.length === 0) {
      return [];
    }
    const { isParking } = this.props;
    if (month === 13) {
      const initItem = {};
      const januaryItem = _.first(
        _.filter(contractPlanItems, item => item.year === year && item.month === 1),
      );
      const items = _.filter(contractPlanItems, item => item.year === year);
      const sumData = _.reduce(
        items,
        (sum, element) => {
          const tempSum = {
            supplyRoomCount: _.round(_.sum([sum.supplyRoomCount, element.supplyRoomCount]), 5),
            supplyCanSignRoomCount: _.round(
              _.sum([sum.supplyCanSignRoomCount, element.supplyCanSignRoomCount]),
              5,
            ),
            supplyRoomArea: _.round(_.sum([sum.supplyRoomArea, element.supplyRoomArea]), 4),
            supplySumPrice: _.round(_.sum([sum.supplySumPrice, element.supplySumPrice]), 4),
            statisticsSignRoomCount: _.round(
              _.sum([sum.statisticsSignRoomCount, element.statisticsSignRoomCount]),
              5,
            ),
            statisticsSignRoomArea: _.round(
              _.sum([sum.statisticsSignRoomArea, element.statisticsSignRoomArea]),
              4,
            ),
            statisticsSignSumPrice: _.round(
              _.sum([sum.statisticsSignSumPrice, element.statisticsSignSumPrice]),
              4,
            ),
          };
          return tempSum;
        },
        initItem,
      );
      if (Object.keys(sumData).length > 0 && Object.keys(januaryItem).length > 0) {
        const supplyItem = {
          supplyRoomCount: sumData.supplyRoomCount,
          supplyCanSignRoomCount: sumData.supplyCanSignRoomCount,
          supplyRoomArea: sumData.supplyRoomArea,
          supplyAvgRoomArea:
            isParking === 1
              ? 0
              : sumData.supplyRoomCount === 0
              ? 0
              : _.round(sumData.supplyRoomArea / sumData.supplyRoomCount, 4),
          supplyAvgPrice:
            isParking === 1
              ? sumData.supplyRoomCount === 0
                ? 0
                : _.round(sumData.supplySumPrice / sumData.supplyRoomCount, 4)
              : sumData.supplyRoomArea === 0
              ? 0
              : _.round(sumData.supplySumPrice / sumData.supplyRoomArea, 4),
          supplySumPrice: sumData.supplySumPrice,
        };
        const statisticsItem = {
          statisticsSignRoomCount: sumData.statisticsSignRoomCount,
          statisticsSignRoomArea: sumData.statisticsSignRoomArea,
          statisticsSignAvgPrice:
            isParking === 1
              ? sumData.statisticsSignRoomCount === 0
                ? 0
                : _.round(sumData.statisticsSignSumPrice / sumData.statisticsSignRoomCount, 4)
              : sumData.statisticsSignRoomArea === 0
              ? 0
              : _.round(sumData.statisticsSignSumPrice / sumData.statisticsSignRoomArea, 4),
          statisticsSignSumPrice: sumData.statisticsSignSumPrice,
          roomCount: _.round(_.sum([januaryItem.earlyRoomCount, supplyItem.supplyRoomCount]), 5),
          canSignRoomCount: _.round(
            _.sum([januaryItem.earlyCanSignRoomCount, supplyItem.supplyCanSignRoomCount]),
            5,
          ),
          roomArea: _.round(_.sum([januaryItem.earlyRoomArea, supplyItem.supplyRoomArea]), 4),
          sumPrice: _.round(_.sum([januaryItem.earlySumPrice, supplyItem.supplySumPrice]), 4),
        };
        return [
          {
            key: 'early',
            name: '年初存货',
            editable: false,
            roomCount: januaryItem.earlyRoomCount,
            canSignRoomCount: null,
            roomArea: januaryItem.earlyRoomArea,
            avgRoomArea: januaryItem.earlyAvgRoomArea,
            avgPrice: januaryItem.earlyAvgPrice,
            sumPrice: _.toNumber(januaryItem.earlySumPrice / 10000),
            signRoomCount: null,
            signRoomArea: null,
            signAvgPrice: null,
            signSumPrice: null,
            isParking,
            errorSignRoomCount: false,
            errorSignSumPrice: false,
          },
          {
            key: 'supply',
            name: '年度新供',
            editable: false,
            roomCount: supplyItem.supplyRoomCount,
            canSignRoomCount: null,
            roomArea: supplyItem.supplyRoomArea,
            avgRoomArea: supplyItem.supplyAvgRoomArea,
            avgPrice: supplyItem.supplyAvgPrice,
            sumPrice: _.toNumber(supplyItem.supplySumPrice / 10000),
            signRoomCount: null,
            signRoomArea: null,
            signAvgPrice: null,
            signSumPrice: null,
            isParking,
            errorSignSumPrice: false,
            errorSignRoomCount: false,
          },
          {
            key: 'statistics',
            name: '年度合计',
            editable: false,

            roomCount: statisticsItem.roomCount,
            canSignRoomCount: statisticsItem.roomCount - statisticsItem.statisticsSignRoomCount,
            roomArea: statisticsItem.roomArea,
            sumPrice: _.toNumber(statisticsItem.sumPrice / 10000),
            avgRoomArea: Math.abs(
              isParking === 1
                ? null
                : statisticsItem.roomCount === 0
                ? 0
                : statisticsItem.roomArea / statisticsItem.roomCount,
            ),
            avgPrice: Math.abs(
              isParking === 1
                ? statisticsItem.roomCount === 0
                  ? 0
                  : statisticsItem.sumPrice / statisticsItem.roomCount
                : statisticsItem.roomArea === 0
                ? 0
                : statisticsItem.sumPrice / statisticsItem.roomArea,
            ),
            signRoomCount: statisticsItem.statisticsSignRoomCount,
            signRoomArea: statisticsItem.statisticsSignRoomArea,
            signAvgPrice: Math.abs(statisticsItem.statisticsSignAvgPrice),
            signSumPrice: _.toNumber(statisticsItem.statisticsSignSumPrice / 10000),
            isParking,
            errorSignSumPrice: false,
            errorSignRoomCount: false,
          },
        ];
      }
      return [];
    }

    const items = _.filter(contractPlanItems, item => item.year === year && item.month === month);
    let item = {};
    if (items && items.length > 0) {
      item = items[0];
    } else {
      return [];
    }
    // 生成 state =》plan
    return [
      {
        key: 'early',
        name: '月初存货',
        editable: item.editable,
        roomCount: item.earlyRoomCount,
        canSignRoomCount: item.earlyCanSignRoomCount,
        roomArea: item.earlyRoomArea,
        avgRoomArea: item.earlyAvgRoomArea,
        avgPrice: item.earlyAvgPrice,
        sumPrice: _.toNumber(item.earlySumPrice / 10000),
        signRoomCount: item.earlySignRoomCount,
        signRoomArea: item.earlySignRoomArea,
        signAvgPrice: item.earlySignAvgPrice,
        signSumPrice: _.toNumber(item.earlySignSumPrice / 10000),
        isParking: item.isParking,
        errorSignRoomCount: item.errorEarlySignRoomCount,
        errorSignSumPrice: item.errorEarlySignSumPrice,
      },
      {
        key: 'supply',
        name: '本月新供',
        editable: item.editable,
        roomCount: item.supplyRoomCount,
        canSignRoomCount: item.supplyCanSignRoomCount,
        roomArea: item.supplyRoomArea,
        avgRoomArea: item.supplyAvgRoomArea,
        avgPrice: item.supplyAvgPrice,
        sumPrice: _.toNumber(item.supplySumPrice / 10000),
        signRoomCount: item.supplySignRoomCount,
        signRoomArea: item.supplySignRoomArea,
        signAvgPrice: item.supplySignAvgPrice,
        signSumPrice: _.toNumber(item.supplySignSumPrice / 10000),
        isParking: item.isParking,
        errorSignRoomCount: item.errorSupplySignRoomCount,
        errorSignSumPrice: item.errorSupplySignSumPrice,
      },
      {
        key: 'statistics',
        name: '本月合计',
        editable: item.editable,
        roomCount: item.statisticsRoomCount,
        canSignRoomCount: item.statisticsCanSignRoomCount,
        roomArea: item.statisticsRoomArea,
        avgRoomArea: item.statisticsAvgRoomArea,
        avgPrice: item.statisticsAvgPrice,
        sumPrice: _.toNumber(item.statisticsSumPrice / 10000),
        signRoomCount: item.statisticsSignRoomCount,
        signRoomArea: item.statisticsSignRoomArea,
        signAvgPrice: item.statisticsSignAvgPrice,
        signSumPrice: _.toNumber(item.statisticsSignSumPrice / 10000),
        isParking: item.isParking,
      },
    ];
  };

  // 获取用户手动输入的金额 --- Begin
  changeSignMoney = (val, rowData, maxSumPrice) => {
    const { year, month, initYear, initMonth } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanProductTypeDetail/changeSignMoney',
      payload: {
        year: year || initYear,
        month: month || initMonth,
        key: rowData.key,
        value: val > maxSumPrice ? maxSumPrice : val,
      },
    });
  };
  // 获取用户手动输入的金额 --- End

  canSignPrice = canSignPrice => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanProductTypeDetail/canSignPrice',
      payload: {
        canSignPrice,
      },
    });
  };

  render() {
    const self = this;
    const { signDates, isParking } = this.props;
    const lastYear = _.last(signDates);
    let stateYear = this.state.year;
    let stateMonth = this.state.month;
    if (!stateYear) {
      stateYear = this.state.initYear;
    }
    if (!stateMonth) {
      stateMonth = this.state.initMonth;
    }
    const plan13 = this.getPlan({
      contractPlanItems: this.props.contractPlanItems,
      year: stateYear * 1,
      month: 13,
    });

    const plan = this.getPlan({
      contractPlanItems: this.props.contractPlanItems,
      year: stateYear * 1,
      month: stateMonth * 1,
    });

    let planLast = [];
    let surplusPrice;
    let surplusArea;
    let surplusCount;
    if (signDates && signDates.length > 0) {
      planLast = this.getPlan({
        contractPlanItems: this.props.contractPlanItems,
        year: lastYear.key,
        month: _.last(lastYear.months).key,
      });
    }
    if (planLast && planLast.length > 2) {
      surplusPrice = planLast[2].sumPrice - planLast[2].signSumPrice;
      surplusArea = planLast[2].roomArea - planLast[2].signRoomArea;
      surplusCount = planLast[2].roomCount - planLast[2].signRoomCount;
    }

    this.canSignPrice(surplusPrice);
    return (
      <Row className={styles.contractPlan} gutter={[0, 10]}>
        <Col span={24}>
          <Row type="flex" justify="space-between" align="middle">
            <Col>
              <b style={{ fontSize: 14 }}>编制新版签约计划</b>
            </Col>
            <Col>
              {!(isParking * 1) ? (
                <span className="color-red">{`组团产品构成剩余可签约：${_.round(
                  surplusPrice,
                  4,
                )} 万元，${_.round(surplusArea, 2)}平米，${_.round(surplusCount, 2)}套`}</span>
              ) : (
                <span className="color-red">{`车位剩余可签：${_.round(
                  surplusPrice,
                  4,
                )}万元 , ${_.round(surplusCount, 2)}个`}</span>
              )}
            </Col>
          </Row>
        </Col>
        <Col span={24}>
          <Row gutter={[0, 10]}>
            <Col span={24}>
              <Tabs
                defaultActiveKey={`${stateYear}`}
                activeKey={`${stateYear}`}
                type="editable-card"
                onEdit={this.onEditYear}
                onChange={this.changeYear}
                hideAdd
                tabBarExtraContent={
                  <Button type="primary" onClick={() => this.onEditYear(null, 'add')}>
                    添加年
                  </Button>
                }
              >
                {signDates &&
                  signDates.length > 0 &&
                  signDates.map(year => (
                    <TabPane
                      closable={year.removable && lastYear.key === year.key}
                      key={`${year.key}`}
                      tab={
                        <span style={year.error ? { color: '#ff4d4f', textAlign: 'center' } : {}}>
                          {year.error ? <Icon type="info-circle" theme="filled" /> : ''}
                          {year.key}
                        </span>
                      }
                    >
                      <Radio.Group value={stateMonth} onChange={this.changeMonth}>
                        {/* <Radio.Button key="13" value={13}>
                          <span>年度合计</span>
                        </Radio.Button> */}
                        {year.months &&
                          year.months.map(month => (
                            <Radio.Button
                              key={`${month.key}`}
                              disabled={!month.clickable}
                              value={month.key}
                            >
                              <span
                                style={month.error ? { color: '#ff4d4f', textAlign: 'center' } : {}}
                              >
                                {month.key}月
                                {month.error ? (
                                  <>
                                    &nbsp;
                                    <Icon type="info-circle" theme="filled" />
                                  </>
                                ) : (
                                  ''
                                )}
                              </span>
                            </Radio.Button>
                          ))}
                      </Radio.Group>
                    </TabPane>
                  ))}
              </Tabs>
            </Col>
            <Col span={24}>
              <Table
                loading={plan && plan.length === 0}
                pagination={false}
                dataSource={plan}
                bordered
                size="middle"
                // size="small"
              >
                <Column
                  title="存货/新供/合计"
                  dataIndex="name"
                  key="name"
                  align="center"
                  className="td-bgcolor"
                  width={150}
                />
                <ColumnGroup title={stateMonth * 1 === 13 ? '年度可售' : '本月可售'}>
                  <Column
                    width={80}
                    title={isParking !== 1 ? '套数' : '车位数'}
                    dataIndex="roomCount"
                    key="roomCount"
                    align="center"
                    render={text => <NumberView precision={2} cellData={text} />}
                  />
                  {/* <Column
                    width={100}
                    title={isParking !== 1 ? '剩余可签套数' : '剩余可签车位数'}
                    dataIndex="canSignRoomCount"
                    key="canSignRoomCount"
                    align="center"
                    render={text => <NumberView precision={2} cellData={text} />}
                  /> */}
                  <Column
                    width={100}
                    title="面积"
                    dataIndex="roomArea"
                    key="roomArea"
                    align="center"
                    render={text => {
                      if (text !== null && isParking !== 1) {
                        return <NumberView precision={2} cellData={text} />;
                      }
                      return '';
                    }}
                  />
                  <Column
                    width={80}
                    title={isParking !== 1 ? '套均面积' : '车位面积'}
                    dataIndex="avgRoomArea"
                    key="avgRoomArea"
                    align="center"
                    render={text => {
                      if (text !== null && isParking !== 1) {
                        return <NumberView precision={2} cellData={text} />;
                      }
                      return '';
                    }}
                  />
                  <Column
                    width={100}
                    title="均价"
                    dataIndex="avgPrice"
                    key="avgPrice"
                    align="center"
                    render={text => <NumberView precision={0} cellData={text} />}
                  />
                  <Column
                    width={100}
                    title="金额(万元)"
                    dataIndex="sumPrice"
                    key="sumPrice"
                    align="center"
                    render={text => <NumberView precision={4} cellData={text} />}
                  />
                </ColumnGroup>
                <ColumnGroup title={stateMonth * 1 === 13 ? '年度签约' : '本月签约'}>
                  <Column
                    width={100}
                    className="td-pid"
                    align="right"
                    title={isParking !== 1 ? '套数' : '车位数'}
                    render={text => <NumberView precision={2} cellData={text} />}
                    dataIndex="signRoomCount"
                    key="signRoomCount"
                  />
                  <Column
                    width={100}
                    title="面积"
                    dataIndex="signRoomArea"
                    key="signRoomArea"
                    align="center"
                    render={text => {
                      if (text !== null && isParking !== 1) {
                        return <NumberView precision={2} cellData={text} />;
                      }
                      return '';
                    }}
                  />
                  <Column
                    width={80}
                    title="均价"
                    dataIndex="signAvgPrice"
                    key="signAvgPrice"
                    align="center"
                    render={text => <NumberView precision={0} cellData={text} />}
                  />
                  <Column
                    width={100}
                    title="金额(万元)"
                    dataIndex="signSumPrice"
                    key="signSumPrice"
                    align="center"
                    render={(text, record, index) => {
                      if ((index === 0 && record.editable) || (index === 1 && record.editable)) {
                        return (
                          <InputEditor
                            precision={4}
                            size="small"
                            cellData={text}
                            rowData={record}
                            validateStatus={record.errorSignSumPrice ? 'error' : 'success'}
                            onChange={val => {
                              self.changeSignMoney(
                                val,
                                record,
                                record.sumPrice > 0 ? record.sumPrice : 0,
                              );
                            }}
                            min={-1000000000}
                          />
                        );
                      }
                      return <NumberView precision={4} cellData={text} />;
                    }}
                  />
                </ColumnGroup>
                <Column
                  title={
                    <>
                      <div>年度累计签约金额</div>(万元)
                    </>
                  }
                  width={140}
                  dataIndex="signSumPricex"
                  key="signSumPricex"
                  align="center"
                  render={(text, record, index) => {
                    if (index === 0 || index === 1) {
                      return '-';
                    }
                    return <NumberView precision={0} cellData={plan13[2].signSumPrice} />;
                  }}
                />
              </Table>
            </Col>
          </Row>
        </Col>
      </Row>
    );
  }
}
